/**
 * 首页脚本
 */
const categorized = loadCategorized()

document.addEventListener("DOMContentLoaded", () => {
  // 加载继续观看
  loadContinueWatching()

  // 加载分类
  loadCategory()

  // 添加动画效果
  addAnimations()
})

function loadCategory(){  
  // 更新导航栏
  const categoryGrid = document.getElementById("categoryGrid")
  categoryGrid.innerHTML = ``
  const categoryItemIcon = {
    movie: '<i class="ri-film-line"></i>',
    tv: '<i class="ri-tv-line"></i>',
    anime: '<i class="ri-movie-line"></i>',
    variety: '<i class="ri-emotion-line"></i>',
    other: '<i class="ri-stack-line"></i>',
  }
  
  categorized.forEach((category) => {
    const categoryItemGrid = document.createElement("a");
    categoryItemGrid.className = "category-card";
    categoryItemGrid.href = `category.html?type=${category.type}`;
    categoryItemGrid.innerHTML = `
              <div class="category-icon">
                ${categoryItemIcon[category.type]}
              </div>
              <h3>${category.name}</h3>
            `;
            categoryGrid.appendChild(categoryItemGrid);
    // 加载媒体分类
    loadMediaList(category)
  });
}


/**
 * 加载继续观看
 */
async function loadContinueWatching() {
  const container = document.getElementById("continueWatchingGrid")
  if (!container) return

  // 获取播放历史
  const history = API.getPlayHistory()

  // 清空加载中状态
  container.innerHTML = ""

  if (history.length === 0) {
    container.innerHTML = `
      <div class="empty-state">
        <i class="ri-history-line"></i>
        <p>暂无观看记录</p>
      </div>
    `
    return
  }

  // 只显示最近的6条记录
  const recentHistory = history.slice(0, 8)

  recentHistory.forEach((item) => {
    const mediaItem = {
      vod_id: item.id,
      vod_name: item.title,
      vod_pic: item.poster,
      vod_remarks: formatTimeAgo(item.timestamp),
    }

    const card = UI.createMediaCard(mediaItem)
    container.appendChild(card)
  })
}

/**
 * 加载媒体分类
 */
async function loadMediaList(category) {
  const mediaList = document.getElementById("mediaList")
  if (!mediaList) return
  if(category.type){
    const mediaTiems =document.createElement("media-section")
    mediaTiems.id = category.type+"Section"
    mediaTiems.className = "media-section"
    mediaTiems.innerHTML = `
      <div class="section-header">
        <h2 class="section-title">${category.name}</h2>
        <a href="category.html?type=${category.type}" class="view-more">
          更多 <i class="ri-arrow-right-s-line"></i>
        </a>
      </div>
      <div class="media-grid" id="${category.type}Grid"></div>
      <div class="media-loading-grid">
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
      </div>
    `
    mediaList.appendChild(mediaTiems)    
    loadMediaListByType(category)
  }
}


/**
 * 加载列表 
 */
async function loadMediaListByType(category) {
  if (!category) return
  const container = document.getElementById(`${category.type}Grid`)
  if (!container) return

  try {
    const activeSource = AppConfig.getActiveSource()
    if (!activeSource) {
      container.innerHTML = `
        <div class="empty-state">
          <i class="ri-tv-2-line"></i>
          <p>请先添加媒体源</p>
        </div>
      `
      return
    }
    // 获取分类ID 取category下subcategories的所有元素的id
    const categoryIds = category.subcategories.map((subcategory) => subcategory.id).join(",")
    
    // 获取列表
    const response = await API.getMediaList(activeSource, 1, categoryIds)

    // 清空加载中状态
    container.innerHTML = ""

    if (response.list.length === 0) {
      container.innerHTML = `
        <div class="empty-state">
          <i class="ri-tv-2-line"></i>
          <p>暂无${category.name}</p>
        </div>
      `
      return
    }
    // 更新category_
    const categorybadge = document.getElementById(`category_${category.type}`)
    categorybadge.textContent = response.total
    // 写入缓存
    window.AppConfig.updateNestedConfig(`cache.total.${category.type}`,response.total)
    // 只显示前8个
    const lists = response.list.slice(0, 8)

    removeListLoading(function(){
      lists.forEach((list) => {
        const card = UI.createMediaCard(list)
        container.appendChild(card)
      })
    })
  } catch (error) {
    console.error(`加载列表失败-${category.type}:`, error)
    container.innerHTML = `
      <div class="error-state">
        <i class="ri-error-warning-line"></i>
        <p>加载失败，请重试</p>
      </div>
    `
  }
}



/**
 * 添加动画效果
 */
function addAnimations() {
  // 为分类卡片添加动画
  const categoryCards = document.querySelectorAll(".category-card")
  categoryCards.forEach((card, index) => {
    card.style.animationDelay = `${index * 0.1}s`
    card.classList.add("fade-in-up")
  })

  // 为页面标题添加动画
  const pageTitle = document.querySelector(".page-title")
  if (pageTitle) {
    pageTitle.classList.add("fade-in")
  }

  // 为分区标题添加动画
  const sectionTitles = document.querySelectorAll(".section-title")
  sectionTitles.forEach((title, index) => {
    title.style.animationDelay = `${0.3 + index * 0.1}s`
    title.classList.add("fade-in")
  })
}

/**
 * 格式化时间为相对时间
 * @param {number} timestamp 时间戳
 * @returns {string} 相对时间
 */
function formatTimeAgo(timestamp) {
  const now = Date.now()
  const diff = now - timestamp

  // 小于1分钟
  if (diff < 60 * 1000) {
    return "刚刚"
  }

  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000))
    return `${minutes}分钟前`
  }

  // 小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return `${hours}小时前`
  }

  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  }

  // 大于30天
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
}
